package com.nuliji.tools.third.amap;

import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.*;

/**
 * Created by gaojie on 2017/11/23.
 */
public class RestApi {
    private static final Logger logger = LoggerFactory.getLogger(RestApi.class);

    // 高德应用的地址
    private static String appKey = "a63ffb92338c6bc12788d963f3aecc5b";

    // 地理编码地址
    private static String geoApi = "http://restapi.amap.com/v3/geocode/geo";

    private static String ipApi = "http://restapi.amap.com/v3/ip";

    private static String districtApi = "http://restapi.amap.com/v3/config/district";

    public static IpInfo getIpInfo(String ip){
        Map<String, String> map = new HashMap<>();
        map.put("ip", ip);
        JSONObject result = execute(ipApi, map);
        IpInfo ipInfo = new IpInfo();
        ipInfo.setProvince(result.getString("province").replace("省", ""));
        ipInfo.setCity(result.getString("city").replace("市", ""));
        ipInfo.setAdcode(result.getString("adcode"));
        ipInfo.setRectangle(result.getString("rectangle"));
        String[] rectang = ipInfo.getRectangle().split(";");
        String[] min = rectang[0].split(",");
        String[] max = rectang[1].split(",");
        ipInfo.setLongitude((Double.valueOf(min[0]) + Double.valueOf(max[0])) / 2);
        ipInfo.setLatitude((Double.valueOf(min[1]) + Double.valueOf(max[1])) / 2);
        return ipInfo;
    }

    public static DistrictInfo getDistrictInfo(String city){
        Map<String, String> map = new HashMap<>();
        map.put("keywords", city);
        JSONObject result = execute(districtApi, map);
        result = result.getJSONArray("districts").getJSONObject(0);
        DistrictInfo districtInfo = new DistrictInfo();
        districtInfo.setAdcode(result.getString("adcode"));
        districtInfo.setName(result.getString("name"));
        districtInfo.setCenter(result.getString("center"));
        districtInfo.setLevel(result.getString("level"));
        String[] center = districtInfo.getCenter().split(",");
        districtInfo.setLongitude(Double.valueOf(center[0]));
        districtInfo.setLatitude(Double.valueOf(center[1]));
        return districtInfo;
    }

    private static JSONObject execute(String api, Map<String, String> params) throws RuntimeException {
        try {
            params.put("key", appKey);
            List<String> keys = new ArrayList<>(params.keySet());
            Collections.sort(keys);
            String paramStr = "";
            for (int i = 0; i < keys.size(); i++) {
                String key = keys.get(i);
                String value = params.get(key);
                value = URLEncoder.encode(value, "UTF-8");
                if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                    paramStr = paramStr + key + "=" + value;
                } else {
                    paramStr = paramStr + key + "=" + value + "&";
                }
            }
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(api + "?" + paramStr)
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();

            logger.info("高德地图返回结果:" + result);
            JSONObject a = JSONObject.parseObject(result);

            if(a.getInteger("status") == 0){
                throw new Exception("地图接口错误"+a.getString("info"));
            }
            return a;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
